<?php
// +----------------------------------------------------------------------
// | Description: 客户
// +----------------------------------------------------------------------
// | Author: zl
// +----------------------------------------------------------------------

namespace app\crm\controller;

use app\admin\controller\ApiCommon;
use app\crm\model\BalanceLog;
use app\crm\model\Setting;
use app\crm\model\SettingCategory;
use app\crm\model\Service;
use app\crm\model\ReturnVist;
use app\crm\model\ReturnVistT;
use app\crm\model\Customer as CustomerModel;
use app\crm\model\TransferShop;
use app\crm\model\CustomerConfig as CustomerConfigModel;
use app\crm\model\CustomerGrade as CustomerGradeModel;
use think\response\Json;
use think\facade\Db;

class Customer3 extends ApiCommon
{
    protected $customerModel;
    protected $customerConfigModel;
    /**
     * 用于判断权限
     * @permission 无限制
     * @allow 登录用户可访问
     * @other 其他根据系统设置
     **/
    public function initialize()
    {
        $action = [
            'permission' => ['shanchu','gaiyuangong','gengxinshijian','chongfukehu'],
            'allow' => ['users', 'info']
        ];
        event('CheckAuth',$action);
        $request = $this->request;
        $a = strtolower($request->action());

        $this->customerModel = new CustomerModel();
        $this->customerConfigModel = new CustomerConfigModel();
        if (!in_array($a, $action['permission'])) {
            parent::initialize();
        }
    }
    public function gengxinshijian()
    {
        if (empty($_FILES['file'])) {
            echo '请选择上传文件';exit;
        }
        $tmp_name = $_FILES['file']['tmp_name'];
        if (empty($tmp_name) || !file_exists($tmp_name)) {
            echo '请选择上传文件';exit;
        }
        // print_r(111);
        // exit;
        $importData = readExcelData($tmp_name);
        // print_r($importData);
        $importData = array_values($importData);
        echo '表格中共计：'.count($importData).'条记录<br><br>';
        $shopNameList = array_values(array_unique(array_column($importData,'1')));
        if(count($shopNameList) != 1){
            // echo '表格中门店超过两个';exit;
            // print_r(array_column($importData,'1'));exit;
        }
        $shop_name = $shopNameList[0];
        $shop_id = Db::name("shop")->where('shop_name','=',$shop_name)->value('shop_id');
        if(!$shop_id){
            echo '门店信息不存在';exit;
        }
        $num = 0;
        // $importData = array_slice($importData,0,9000);
        // print_r(count($importData));exit();
        foreach ($importData as $key => $val){
            $where = [];
            if(empty($val[0])){
                continue;
            }
            // if($key<10000){
            //     continue;
            // }
            // if($key>=5000){
            //     continue;
            // }
            array_push($where,['telephone','=',$val[0]]);
            array_push($where,['shop_id','=',$shop_id]);
            $update = [
                    'create_time'=> strtotime($val[2].' 00:00:00')
                ];
            $res = Db::name("customer")->where($where)->update($update);
            $num = $res ? $num + 1 : $num;
            // continue;
        }
        echo '处理完成-'.$shop_name.'-'.$num;exit;
    }
    public function gaiyuangong()
    {
        // if (empty($_FILES['file'])) {
        //     echo '请选择上传文件';exit;
        // }
        // $tmp_name = $_FILES['file']['tmp_name'];
        // if (empty($tmp_name) || !file_exists($tmp_name)) {
        //     echo '请选择上传文件';exit;
        // }
        // // print_r(111);
        // // exit;
        // $importData = readExcelData($tmp_name);
        // // print_r($importData);
        // $importData = array_values($importData);
        // echo '表格中共计：'.count($importData).'条记录<br><br>';
        // $shopNameList = array_values(array_unique(array_column($importData,'1')));
        // if(count($shopNameList) != 1){
        //     echo '表格中门店超过两个';exit;
        // }
        // $shop_name = $shopNameList[0];
        // $shop_id = Db::name("shop")->where('shop_name','=',$shop_name)->value('shop_id');
        // if(!$shop_id){
        //     echo '门店信息不存在';exit;
        // }
        // $kfList = array_values(array_unique(array_column($importData,'2')));
        // $where = [];
        // array_push($where,['realname','in',$kfList]);
        // // array_push($where,['shop_id','=',$shop_id]);
        // // print_r($where);exit;
        // $kfList = Db::name("admin_user")->where($where)->column('id','realname');
        // // print_r($kfList);exit;
        // $updateList = [];
        // foreach ($importData as $key => $val){
        //     $kfIds = $kfList[$val[2]] ?? '';
        //     if(empty($kfIds)){
        //         echo '客服不存在-'.$val[0].'<br>';
        //         continue;
        //     }
        //     $one = $updateList[$kfIds] ?? [];
        //     $phone = $one['phone'] ?? [];
        //     array_push($phone,$val[0]);
        //     $thisData = [
        //             'phone' => $phone,
        //             'kfid' => $kfIds,
        //             'kfname' => $val[2]
        //         ];
        //     $updateList[$kfIds] = $thisData;
        // }
        // $num = 0;
        // foreach ($updateList as $key => $val){
        //     $where = [];
        //     array_push($where,['telephone','in',$val['phone']]);
        //     array_push($where,['shop_id','=',$shop_id]);
        //     $update = [
        //             'creator_id'=> $val['kfid'],
        //             'operator'=> $val['kfid']
        //         ];
        //     $res = 0;
        //     $res = Db::name("customer")->where($where)->update($update);
        //     echo '客服-'.$val['kfname'].'-'.$res.'<br>';
        //     $num = bcadd($num,$res);
        //     // continue;
        // }
        // echo '处理完成-'.$shop_name.'-'.count($kfList).'-'.$num;exit;
    }
    /**
     * 处理直营店客户的余额数据
     */
    public function shanchu()
    {
        // $shop_id = '73782774813542';
        // $ids = Db::name("customer")->where('shop_id','=',$shop_id)->column('id');
        // if(!$ids){
        //     print_r('没有客户');exit;
        // }
        // print_r('客户共计：'.count($ids).'<br>');
        // $res = 0;
        // $res2 = 0;
        // $res3= 0;
        // $res = Db::name("customer")->where('shop_id','=',$shop_id)->delete();
        // $res2 = Db::name("customer_balance")->where('customer_id','in',$ids)->delete();
        // $res3 = Db::name("customer_scar")->where('customer_id','in',$ids)->delete();
        // print_r('客户删除了：'.$res.'<br>');
        // print_r('客户余额记录删除了：'.$res2.'<br>');
        // print_r('客户疤痕记录删除了：'.$res2.'<br>');
        // exit;
        // $where = [];
        // array_push($where,['telephone','<>','0']);
        // array_push($where,['telephone','<>','2147483647']);
        // $list = Db::name("customer")->where($where)->group('telephone')->field('telephone,COUNT(id) as num')->having('num > 1')->select()->toArray();
        // $phones = array_values(array_unique(array_column($list,'telephone')));
        // array_push($where,['telephone','in',$phones]);
        // $res = Db::name("customer")->where($where)->field('id,shop_id,telephone')->select()->toArray();
        // $a = [];
        // $del = [];
        // foreach ($res as $key => $val){
        //     if(isset($a[$val['shop_id']]) && in_array($val['telephone'],$a[$val['shop_id']])){
        //         // $del[] = $val['id'];
        //     }else{
        //         $a[$val['shop_id']][] = $val['telephone'];
        //     }
        // }
        // // $res = Db::name("customer")->where('id','in',$del)->delete();
        // print_r(count($del));exit;
        $res = Db::name("customer_balance")->group('customer_id')->field('customer_id,COUNT(id) as num')->having('num > 3')->select()->toArray();
        $customerIds = array_values(array_unique(array_column($res,'customer_id')));
        $res2 = Db::name("shop_order")->where('uid','in',$customerIds)->group('uid')->column('uid');
        $res3 = Db::name("shop_refund_order")->where('uid','in',$customerIds)->group('uid')->select();
        $del = [];
        foreach ($res as $key => $val){
            $a = Db::name("customer_balance")->where('customer_id','=',$val['customer_id'])->select()->toArray();
            if(count($a)>3){
                foreach ($a as $k => $v){
                    if($k>1){
                        array_push($del,$v['id']);
                    }
                }
            }
        }
        Db::name("customer_balance")->where('id','in',$del)->delete();
        // print_r(count($del));exit;
        print_r($del);exit;
    }
    /**
     * 处理直营店客户的余额数据
     */
    public function chongfukehu()
    {
        // 获取重复用户数据
        $phonelist = Db::name("a_k3yue_jilu")
                // ->group('telephone')
                // ->having('COUNT(telephone) > 1')
                ->column('customer_id');
        // if(empty($phonelist)){
        //     print_r('没有重复数据');exit();
        // }
        $phones = array_values(array_unique($phonelist));
        $clist = Db::name("customer")
                // ->where('telephone','in',$phones)
                ->where('id','in',$phones)
                ->field('id,customer_name,shop_id,king_no,telephone,fcustId')
                ->order('id asc')
                ->select()
                ->toArray();
        $id = array_values(array_unique(array_column($clist,'id')));
        $balanceList = Db::name("customer_balance")
                        ->where('customer_id','in',$id)
                        ->select()
                        ->toArray();
        $slist = Db::name("shop")
                    ->column('shop_name','shop_id');
        $bList = [];
        foreach ($balanceList as $key => $val){
            $bList[$val['id']][] = $val;
        }
        $daochu = [];
        foreach ($clist as $key => $val){
            $d1 = [];
            $thisOne['id'] = $val['id'];
            $thisOne['customer_name'] = $val['customer_name'];
            $thisOne['shop_name'] = $slist[$val['shop_id']] ?? '';
            $thisOne['telephone'] = $val['telephone'];
            $thisOne['fcustId']   = $val['fcustId'];
            $thisOne['king_no']   = $val['king_no'];
            $thisOne['bh_benjin'] = 0;
            $thisOne['bh_zengjin']= 0;
            $thisOne['xm_benjin'] = 0;
            $thisOne['xm_zengjin']= 0;
            $thisB = $bList[$val['id']] ?? [];
            if($thisB){
                foreach ($thisB as $key => $val){
                    if ($val['balance_category_id'] == 1) {
                        // code...
                        $thisOne['bh_benjin'] = $val['money'];
                        $thisOne['bh_zengjin']= $val['complimentary_money'];
                    }else{
                        $thisOne['xm_benjin'] = $val['money'];
                        $thisOne['xm_zengjin']= $val['complimentary_money'];
                    }
                }
            }
            array_push($daochu,$thisOne);
        }
        $callName = [
                    'id'   =>'系统id',
                    'customer_name'   =>'客户名称',
                    'shop_name'  =>'店铺名称',
                    'telephone'  =>'手机号',
                    'fcustId'    =>'金蝶内码',
                    'king_no'    =>'金蝶编码',
                    'bh_benjin'  =>'疤痕本金',
                    'bh_zengjin' =>'疤痕增金',
                    'xm_benjin'  =>'项目本金',
                    'xm_zengjin' =>'项目增金'
                ];
        $downUrl = exportExcelData('重复客户',$callName,$daochu,'xlsx',1);
        print_r('http://'.$_SERVER['HTTP_HOST'].$downUrl);exit;    
    }
}
